<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>DTPG&trade; Route Manager</title>
<!--<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />-->
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key=AIzaSyBzupUgxVoM4Pb2roT72SBLYDO1Mcc0hn8&sensor=true"></script>

<style type="text/css">
	body {
		font-family: sans-serif;
		font-size: 11px;
		background: #efefef;
		color: #333;
		margin-bottom:0px;
		margin-top:0px;
	}
	
	#directions_panel {
		float:right;
		padding-left:2%;
		padding-right:2%;
		padding-top:20px;
		padding-bottom:20px;
		background-color:#ffffff;
		color:#666;
		width:26%;
		height:460px;
		overflow-y:auto;
	}
	
	#map_canvas {
		float:left;
		width:70%;
		height:500px;
	}

	#outputDiv {
		padding:20px 20px 20px 20px;
		font-family: monospace;
		background:#ccc;
		color:#333;
		max-height:100px;
		overflow-y:auto;
	}
	
</style>

<script type="text/javascript">
	var directionDisplay;
	var directionsService = new google.maps.DirectionsService();
	var map;
	var num_waypoints = 0;
	var alpha = 0.5;
	var geocoder;

	function initialize() {
		directionsDisplay = new google.maps.DirectionsRenderer();
		var wburg = new google.maps.LatLng(37.2710135, -76.707457);
		var myOptions = {
			zoom: 15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			center: wburg
		}
		
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		geocoder = new google.maps.Geocoder();
		directionsDisplay.setMap(map);
		
	}

	function plotRoute(routeStr) {

		routeStr = "0," + routeStr;
		var routeList = routeStr.split(",");
		
		var address_list = [];
		var pickups = document.getElementsByName('pickup[]');
		var dropoffs = document.getElementsByName('dropoff[]');
		var sizes = document.getElementsByName('numpeople[]');
		var waits = document.getElementsByName('waittime[]');
		
		address_list.push(document.getElementById('current').value);

		for (var i = 0; i < pickups.length; i++) {
			address_list.push(pickups[i].value);
		}

		for (var i = 0; i < dropoffs.length; i++) {
			address_list.push(dropoffs[i].value);
		}

		var start = address_list[0];
		var end = address_list[parseFloat(routeList[routeList.length-1])]

		var waypts = [];
		
		for (var i = 1; i < routeList.length-1; i++) {
			waypts.push({
				location:address_list[parseFloat(routeList[i])],
				stopover:true});
		}
		
		var request = {
			origin: start, 
			destination: end,
			waypoints: waypts,
			optimizeWaypoints: false,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {

				directionsDisplay.setDirections(response);
				var route = response.routes[0];
				var summaryPanel = document.getElementById("directions_panel");
				summaryPanel.innerHTML = "";
				
				// For each route, display summary information.
				for (var i = 0; i < route.legs.length; i++) {
					var routeSegment = i + 1;
					summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";

					var startIndex = parseFloat(routeList[i]);
					var startLocType = "Van: ";

					if (startIndex > dropoffs.length) {
						startLocType = "Dropoff: ";
						startIndex -= dropoffs.length;
					} else if (startIndex > 0) {
						startLocType = "Pickup: ";
					}

					var endIndex = parseFloat(routeList[i+1]);
					var endLocType = "Pickup: ";

					if (endIndex > dropoffs.length) {
						endLocType = "Dropoff: ";
						endIndex -= dropoffs.length;
					}


					route.legs[i].start_address += " ("+startLocType+sizes[startIndex].value+" People)";
					summaryPanel.innerHTML += route.legs[i].start_address + " to ";
					route.legs[i].end_address += " ("+endLocType+sizes[endIndex].value+" People)";
					summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
					summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
				}
				directionsDisplay.setPanel(summaryPanel);
			}
		});
	}

	function calculateDistances() {
	
		var address_list = [];
		var pickups = document.getElementsByName('pickup[]');
		var dropoffs = document.getElementsByName('dropoff[]');


		address_list.push(document.getElementById('current').value);

		for (var i = 0; i < pickups.length; i++) {
			address_list.push(pickups[i].value);
		}

		for (var i = 0; i < dropoffs.length; i++) {
			address_list.push(dropoffs[i].value);
		}

		var service = new google.maps.DistanceMatrixService();
		service.getDistanceMatrix(
			{
				origins: address_list,
				destinations: address_list,
				travelMode: google.maps.TravelMode.DRIVING,
				unitSystem: google.maps.UnitSystem.METRIC,
				avoidHighways: false,
				avoidTolls: false
			}, callback);
	}
	
	function callback(response, status) {
		if (status != google.maps.DistanceMatrixStatus.OK) {
			alert('Error was: ' + status);
		} else {
			var origins = response.originAddresses;
			var destinations = response.destinationAddresses;
			var outputDiv = document.getElementById('outputDiv');
			var numDropoffs = document.getElementsByName('dropoff[]').length;
			command = 'python ../../route/routing.py ';

			for (var i = 0; i < origins.length; i++) {
				var results = response.rows[i].elements;
				var assocID = 'None';//(i > numDropoffs ? i-numDropoffs : 'None');
				var index =  i > numDropoffs ? i-numDropoffs : i;
				var size = document.getElementsByName('numpeople[]')[index].value;
				if (size == '') size = 1;
				var wait = 0;

				if (i > numDropoffs) { // Dropoff location
					assocID = i - numDropoffs;
					size *= -1;
					wait = document.getElementsByName('waittime[]')[index].value;
				}

				if (wait == '') wait = 0;

				command += "'"+i+";"+ assocID +";"+size+";"+wait+";";
				for (var j = 0; j < results.length; j++) {
					command += j+"="+results[j].duration.value+",";
				}

				command = command.slice(0,-1); // trailing comma
				command += "' ";
			}

			optimizeRoute(command);
		}
	}

	function optimizeRoute(command) {

		var xmlhttp;

		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}

		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				var route = xmlhttp.responseText;
				document.getElementById('outputDiv').innerHTML += ">>> " + command + "<br/>" + route + "<br/>";
				if (route != "Error") {
					plotRoute(route);
				}
			}
		}
		
		xmlhttp.open("GET","../shared/optimize.php?cmd="+command,true);
		xmlhttp.send();
	}

	function addLocation() {
		num_waypoints++;
		var table = document.getElementById('address_list');
		var num_rows = table.rows.length;
		
		for(var i = 2; i < num_rows; i++) {
			table.rows[i].cells[0].innerHTML = 'Stop ' + (i-1);
			table.rows[i].cells[5].innerHTML = '<a href="#" onclick="deleteLocation(' + (i) + ')">X</a>';
		}
		
		var row = table.insertRow(num_rows);
		var cell0 = row.insertCell(0);
		cell0.innerHTML = "Stop "+(num_rows-1);
		var cell1 = row.insertCell(1);
		var pickup = document.createElement("input");
		pickup.name = "pickup[]";
		cell1.appendChild(pickup);
		
		var dropOff = document.createElement("input");
		dropOff.name = "dropoff[]";
		var cell2  = row.insertCell(2);
		cell2.appendChild(dropOff);
		
		var numPeople = document.createElement("input");
		numPeople.name = "numpeople[]";
		var cell3 = row.insertCell(3);
		cell3.appendChild(numPeople);

		var waitTime = document.createElement("input");
		waitTime.name = "waittime[]";
		var cell4 = row.insertCell(4);
		cell4.appendChild(waitTime);

		var cell5 = row.insertCell(5);
		cell5.innerHTML = '<a href="#" onclick="deleteLocation(' + (num_rows) + ')">X</a>';
	}
	
	function deleteLocation(row_index) {
		var table = document.getElementById('address_list');
		table.deleteRow(row_index);
		
		var num_rows = table.rows.length;
		
		for(var i = 2; i < num_rows; i++) {
			table.rows[i].cells[0].innerHTML = 'Stop ' + (i-1);
			table.rows[i].cells[5].innerHTML = '<a href="#" onclick="deleteLocation(' + i + ')">X</a>';
		}
		
	}
</script>
</head>
<body onload="initialize()">
<div id="control_panel" style="width:100%;text-align:left;">
<div style="margin-top:20px;margin-bottom:20px;border-width:2px;">
<b>DTPG&trade; Route Manager</b> <br />
<div id="inputs">
	<button type="button" onclick="addLocation();">Add Location</button>
	<input type="submit" onclick="calculateDistances();" />
	<table id="address_list">
		<tr>
			<td>Current</td>
			<td><input name="current" id="current"/></td>
			<td>&nbsp;</td>
			<td><input name="numpeople[]" id="numpeople[]"/></td>
			<td><input name="waittime[]" id="waittime[]"/></td>
		</tr>
		<tr>
			<th>&nbsp;</th>
			<th>Pickup</th>
			<th>Dropoff</th>
			<th>Size</th>
			<th>Wait</th>
		</tr>
	</table>
	<div id="next_address"></div>
</div>
<br />
<button type="button" onclick="addLocation();">Add Location</button>
<input type="submit" onclick="calculateDistances();" />
</div>
<div id="directions_panel"></div>
<div id="map_canvas"></div>
<div style="clear:both"></div>
<div id="outputDiv"></div>
</body>
</html>
